
from django.contrib.auth.backends import ModelBackend
from apps.users.models import User
import re


# 封装 判断 用户输入 账号类型
def judge_accounts_type(accounts):

    try:
        if re.match(r"^1[345789]\d{9}$", accounts):
            user = User.objects.get(mobile=accounts)
        else:
            user = User.objects.get(username=accounts)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """前后端不分离写的验证方法"""
    # 重写 authenticate 方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = judge_accounts_type(username)

        # 判断密码是否正确
        if user and user.check_password(password):
            return user


# 前后分离的验证
class MeiduoModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断是否为 vue 组件发送的信息
        if request is None:
            try:
                if re.match(r"^1[3-9]\d{9}$", username):
                    user = User.objects.get(mobile=username, is_staff=True)
                else:
                    user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            if user.check_password(password):
                return user
        else:
            try:
                if re.match(r'^1[3-9]\d{9}$', username):
                    user = User.objects.get(mobile=username)
                else:
                    user = User.objects.get(username=username)
            except:
                return None
            if user.check_password(password):
                return user
            else:
                return None


